import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:logger/logger.dart';

typedef LightBrightnessBarallback = void Function(double value);

// 灯光亮度控制滑动进度条
class LightBrightnessBar extends StatefulWidget {
  const LightBrightnessBar(
      {super.key,
      required this.value,
      this.barColor = Colors.white,
      this.barHeight = 50,
      this.iconColor = const Color.fromRGBO(50, 50, 50, 0.8),
      this.backgroundColor = const Color.fromRGBO(50, 50, 50, 0.8),
      required this.valueChanged});

  final double value; // 当前百分比
  final Color barColor; // 进度条颜色
  final double barHeight; // 进度条宽度
  final Color backgroundColor; // 背景色
  final Color iconColor; // 按钮背景色
  final LightBrightnessBarallback valueChanged; // 手势停止返回

  @override
  State<LightBrightnessBar> createState() {
    return _LightBrightnessBarState();
  }
}

// 混入 AutomaticKeepAliveClientMixin 进行组件缓存
class _LightBrightnessBarState extends State<LightBrightnessBar>
    with AutomaticKeepAliveClientMixin {
  double _superHeight = 0;
  double _superWidth = 0;
  // 进度条宽度
  double _progressValue = 0;
  // 是否是手动拖动
  bool _dragStart = false;
// 设置为 true 则表示保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  void didUpdateWidget(covariant LightBrightnessBar oldWidget) {
    _progressValue = _superWidth * widget.value;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 获取到组件高度直接创建页面
    return LayoutBuilder(builder: (context, constraints) {
      if (_superHeight == 0) {
        _superHeight = constraints.biggest.height; // 获取组件在父组件所能设置的最大高度
        _superWidth = constraints.biggest.width;
        _progressValue = _superWidth * widget.value;
      }
      return _buildProgressWidget(context);
    });
  }

  Widget _buildProgressWidget(BuildContext context) {
    return GestureDetector(
        onHorizontalDragDown: (value) {
          // print('手指按下');
        },
        onHorizontalDragStart: (value) {
          // print('手指开始横向滑动');
          _dragStart = true;
        },
        onHorizontalDragUpdate: (value) {
          double newOffset = _progressValue + value.delta.dx;

          if (newOffset >= 0 && newOffset <= _superWidth) {
            Logger().d(
                '正在横向滑动-${value.delta}\n ---新位置：$newOffset ------- 顶部距离== $_progressValue');
            _progressValue = newOffset;
            double percent = newOffset / _superWidth;
            double percentP = double.parse(percent.toStringAsFixed(2));
            if (percentP == 0) {
              _progressValue = 0;
            } else if (percentP == 1) {
              _progressValue = _superWidth;
            }
            Logger().d('滑动百分比:$percentP');
            widget.valueChanged(percentP);
            setState(() {});
          }
        },
        onHorizontalDragEnd: (value) {
          // print('手指垂直滑动结束');
          _dragStart = false;
          setState(() {});
        },
        onHorizontalDragCancel: () {
          // print('滑动取消');
          _dragStart = false;
        },
        child: Container(
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            color: widget.backgroundColor,
          ),
          height: widget.barHeight,
          child: Stack(
            alignment: AlignmentDirectional.centerStart,
            children: [
              AnimatedContainer(
                duration: Duration(milliseconds: _dragStart ? 0 : 300),
                curve: Curves.easeOutCubic,
                width: _progressValue,
                color: widget.barColor,
              ),
              AnimatedPositioned(
                duration: Duration(milliseconds: _dragStart ? 0 : 300),
                curve: Curves.easeOutCubic,
                left: _iconPosion,
                child: Container(
                  width: 4.w,
                  height: 22.h,
                  decoration: BoxDecoration(
                      color: widget.iconColor,
                      borderRadius: BorderRadius.circular(2.r)),
                ),
              ),
            ],
          ),
        ));
  }

  double get _iconPosion {
    double iconPosion = 4.r;
    // 设置icon图标
    if (_progressValue <= 4.r + 8.r) {
      iconPosion = 4.r;
    } else {
      iconPosion = _progressValue - 8.r;
    }
    return iconPosion;
  }
}
